<template>
  <div class="w-full">
    <ClientOnly>
      <template #fallback>
        <!-- 加载中 -->
        <div class="border rounded bg-gray-50 flex items-center justify-center" style="width: 94px;height: 94px;">
          <n-spin :show="true"/>
        </div>
      </template>

      <n-upload
          v-model:file-list="fileList"
          :action="action"
          :data="data"
          :headers="headers"
          :max="max"
          :multiple="max > 1"
          :on-error="handleError"
          :on-finish="handleSuccess"
          accept="image/png,image/jpeg,image/gif"
          list-type="image-card"
          name="file"
      >

      </n-upload>
    </ClientOnly>
  </div>
</template>
<script setup>

const {action, headers} = useUploadConfig();

const props = defineProps({
  // 双向绑定
  modelValue: [String, Array],

  // 数据
  data: {
    type: Object,
    default: () => {
    }
  },

  max: {
    type: Number,
    default: () => 1
  }
})

// 引用事件
const emits = defineEmits(["update:modelValue"]);

// 数据
const fileList = ref([]);


// 上传成功
const handleSuccess = (...e) => {
  const {file, event} = e[0]
  const response = JSON.parse(event.target.response);
  file.url = response.data;
  return file;
}

// 上传失败
const handleError = () => {
  const {message} = createDiscreteApi(['message']);
  message.error = '上传失败'
}


// 初始化fileList
function initFileList() {
  if (typeof props.modelValue === "string") {
    fileList.value = props.modelValue ? [
      {
        id: props.modelValue,
        name: props.modelValue,
        status: 'finished',
        url: props.modelValue,
      }
    ] : []
  } else {
    fileList.value = props.modelValue.map(url => {
      return {
        id: url,
        name: url,
        status: 'finished',
        url: url,
      }
    })
  }
}

// 监听fileList
const stopWatch = watch(() => fileList.value, () => {
  updateModelValue();
}, {
  deep: true
})

// 监听上传后方法
const updateModelValue = () => {
  let urls = [];
  fileList.value.forEach((o) => {
    if (o.status === 'finished' && o.url) {
      urls.push(o.url);
    }
  });
  emits('update:modelValue', props.max === 1 ? (urls[0] || "") : urls);
}


initFileList();
onBeforeUnmount(() => stopWatch());
</script>
